package cn.learn.pay.wechat.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.util.SortedMap;

/**
 * 支付到零钱包的签名规则
 * https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=4_3
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年09月02日22:30
 */
public class SignUtil {

    /**
     * 创建签名
     *
     * @param map        按照参数名ASCII字典序排序
     * @param partnerKey
     * @return
     */
    public static String createSign(SortedMap<String, String> map, String partnerKey) {
        StringBuilder sb = new StringBuilder();
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (StringUtils.isNotBlank(value) && !"sign".equals(key) && !"key".equals(key)) {
                sb.append(key).append("=").append(value);
            }
        }
        sb.append("key=").append(partnerKey);
        return DigestUtils.md5DigestAsHex(sb.toString().getBytes()).toUpperCase();
        //return MD5Encode(sb.toString(), StandardCharsets.UTF_8.name()).toUpperCase();
    }

    /**
     * MD5签名
     * @param origin
     * @param charsetname
     * @return
     */
    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuilder resultSb = new StringBuilder();
        for (byte value : b) {
            resultSb.append(byteToHexString(value));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

}
